import cvxpy as cp
import numpy as np
import time
x = cp.Variable(shape=2)
Q = np.array([[2, 0], [0, 2]])
c = np.array([[-2], [-6]])
A = np.array([[1, 1], [-1, 2], [2, 1]])
b = np.array([[2, 2, 3]])

cost = cp.Minimize(0.5 * cp.quad_form(x, Q) + c.T @ x)
constraints = [A @ x <= b]
problem = cp.Problem(cost, constraints)
problem.solve()
print("最优值：", problem.value)
print("最优变量x1：", x[0].value)
print("最优变量x2：", x[1].value)

accuracy = 1e-6
#  定义求解器列表（含参数）
solvers = [
    {"name": "ECOS", "solver": cp.ECOS, "params": {"reltol": accuracy}},
    {"name": "SCS", "solver": cp.SCS, "params": {"eps": accuracy}},
    {"name": "OSQP", "solver": cp.OSQP, "params": {"eps_rel": accuracy}},
    {"name": "CVXOPT", "solver": cp.CVXOPT, "params": {"reltol": accuracy}},
]

#  循环求解，记录结果
results = {}
for solver in solvers:
    name = solver["name"]
    func = solver["solver"]
    params = solver["params"]

    try:
        start_time = time.time()
        for i in range(100):
            problem.solve(solver=func, **params)
        end_time = time.time()

        if problem.status == cp.OPTIMAL:
            results[name] = {
                "time": end_time - start_time,  # 求解时间（秒）
                "objective": problem.value,  # 目标函数值
                "x1": x[0].value,  # 变量x1值
                "x2": x[1].value,  # 变量x2值
                "iterations": problem.solver_stats.num_iters if hasattr(problem.solver_stats, "num_iters") else None,
                # 迭代次数
                "status": "Success"
            }
        else:
            results[name] = {"status": "Failed", "message": problem.status}
    except Exception as e:
        results[name] = {"status": "Error", "message": str(e)}

# 打印结果（表格形式）
import pandas as pd

df = pd.DataFrame(results).T
print("QCQP问题求解器性能对比：")
print(df[["time", "objective", "x1", "x2", "iterations", "status"]])